package com.yxjx.duoxue;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.service.notification.StatusBarNotification;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.View;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.LocationClient;
import com.joboevan.push.tool.PushManager;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGLocalMessage;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;
import com.umeng.update.UmengUpdateAgent;
import com.yxjx.duoxue.activities.ActivitiesPageFragment;
import com.yxjx.duoxue.ad.AdPageActivity;
import com.yxjx.duoxue.course.CitySwitchActivity;
import com.yxjx.duoxue.course.CourseListActivity;
import com.yxjx.duoxue.course.CourseSearchActivity;
import com.yxjx.duoxue.course.HomePageFragment;
import com.yxjx.duoxue.customview.autolist.AutoListView;
import com.yxjx.duoxue.database.YxDataBase;
import com.yxjx.duoxue.datamodel.DMCallRecord;
import com.yxjx.duoxue.datamodel.DMOpenApp;
import com.yxjx.duoxue.datamodel.DMReg;
import com.yxjx.duoxue.datamodel.ResponseObject;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.mta.stat.StatHelper;
import com.yxjx.duoxue.my.MyPageActivity;
import com.yxjx.duoxue.my.MyPageFragment;
import com.yxjx.duoxue.my.UserLoginActivity;
import com.yxjx.duoxue.my.UserRegActivity;
import com.yxjx.duoxue.network.MsgCode;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.push.PushHelper;
import com.yxjx.duoxue.utils.MacAddrHelper;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;
import com.yxjx.duoxue.versionupdate.UpdateManager;

public class HomePageActivity extends BaseActionBarActivity {

	public static final int REQUEST_CODE_GET_CITY_NAME = 1;
	public static final int REQUEST_CODE_LOGIN = 2;
	public static final int REQUEST_CODE_ADD_KEYWORDS = 3;
	public static final int REQUEST_CODE_LOGIN_FOR_H5_PAGE = 4;
	public static final String KEY_CITY_NAME = "KEY_CITY_NAME";
	
	private boolean isUploadingData = false;
	
	private String mLastTab = "";
	
	HashMap<String, String> mKeyName = new HashMap<String, String>();
	private int pressedTimes = 0;
	private Context mContext;

	@SuppressLint("NewApi") @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_main_page);
		customizeSearchActionBar(R.layout.head_home_page);
		
		mContext = this;

		View indicator = null;
		String[] resNames = new String[] { "精彩课程", "亲子活动", "我的" };
		final String[] specNames = new String[] { "findCourse", "audition",
				"me" };

		final int[] tabIndicatorRes = new int[] {
				R.drawable.selector_tab_course,
				R.drawable.selector_tab_activity, R.drawable.selector_tab_my };

		for (int i = 0; i < resNames.length; i++) {
			mKeyName.put(specNames[i], resNames[i]);
		}
		
		Class<?>[] classNames = new Class<?>[] { HomePageFragment.class,
				ActivitiesPageFragment.class, MyPageFragment.class };
		mLastTab = specNames[0];
		
		
		addHomePageListener();
		
		// intent;
		Bundle extra = getIntent().getExtras();
		
		// 本地推送
		try {
			registerXgNotification();
			boolean isPushReady = PushManager.getInstance().connect(getApplicationContext(), true);
			boolean isOpenRemind = PushManager.getInstance().isOpenRemind(
					getApplicationContext(), true, "你错过了吗？你没来的几天，多学更新了很多精彩课程和亲子活动，快来看看吧", 7, 18,
					19);
			Utils.logd("XXYY isPushReady = " + isPushReady + ", isOpenRemind = " + isOpenRemind);
		} catch (Throwable t) {
			// workround 
			Utils.logd("unexcepted error happen when XG init, t = " + t.getStackTrace());
		}
		
		// MTA
		StatHelper.addKVEvent(mContext, "event_home_start");
		
		
	}

	/**
	 * It doesn't work
	 * @deprecated
	 */
	private void customizeStatusbarBg() {
		// create our manager instance after the content view is set
	    SystemBarTintManager tintManager = new SystemBarTintManager(this);
	    // enable status bar tint
	    tintManager.setStatusBarTintEnabled(true);
	    // enable navigation bar tint
	    tintManager.setNavigationBarTintEnabled(true);
	    tintManager.setStatusBarTintColor(getResources().getColor(R.color.yx_green_home));
	}

	/**
	 * // 增加一个7天后的local notification
	 * @deprecated
	 */
	private void addUserReminderNotification() {
		// 先清除本地通知
		XGPushManager.clearLocalNotifications(getApplicationContext());
		// 注册一个7天后的本地通知
		XGLocalMessage msg = new XGLocalMessage();
		msg.setTitle("你错过了吗？");
		msg.setContent("你没来的几天，多学更新了很多精彩课程和亲子活动，快来看看吧");
		String[] date = Utils.getReminderDate();
//		msg.setDate(date[0]);
//		msg.setHour(date[1]);
//		msg.setMin(date[2]);
		
		msg.setDate("20141223");
		msg.setHour("17");
		msg.setMin("15");
		Utils.logd("XXYY提醒用户 " + date[0]+date[1]+date[2]);
		XGPushManager.addLocalNotification(getApplicationContext(), msg);
	}

	private void registerXgNotification() {
		// XG enable, 在Home界面去注册, 首先尝试将用户手机号作为account进行信鸽注册，否者做普通的注册。
		XGPushConfig.enableDebug(getApplicationContext(), Development.DEV_MODE);
		XGIOperateCallback xgRegCallback = new XGIOperateCallback() {
			@Override
			public void onSuccess(Object data, int flag) {
				Log.d("TPush", "注册成功，设备token为：" + data);
			}

			@Override
			public void onFail(Object data, int errCode, String msg) {
				Log.d("TPush", "注册失败，错误码：" + errCode + ",错误信息：" + msg);
			}
		};
		
		String xgAccount = Utils.getXgPushId(getApplicationContext());
		if (UIHelper.isEmpty(xgAccount)) {
			XGPushManager.registerPush(getApplicationContext(), xgRegCallback);
			Log.d("TPush", "尝试成功");
		} else {
			XGPushManager.registerPush(getApplicationContext(), xgAccount, xgRegCallback);
			Log.d("TPush", "尝试注册 xgAccount1 = " + xgAccount);
		}
	}
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);
		if (arg0 == REQUEST_CODE_GET_CITY_NAME) {
			switch (arg1) {
			case RESULT_OK:
				String cityName = arg2.getStringExtra(KEY_CITY_NAME);
				UIHelper.setText(mActionBar.getCustomView(), R.id.city_name, cityName);
				break;
			default:
				break;
			}
		// 登录	
		} else if (arg0 == REQUEST_CODE_LOGIN) {
			switch (arg1) {
			default:
				break;
			}
		} else if (arg0 == REQUEST_CODE_ADD_KEYWORDS) {
			if (arg1 == RESULT_OK) {
				
			}
		} else if (arg0 == REQUEST_CODE_LOGIN_FOR_H5_PAGE) {
			switch (arg1) {
			case RESULT_OK:
				Intent intent = arg2;
				intent.setClass(HomePageActivity.this, AdPageActivity.class);
				String fixedUrl = arg2.getExtras().getString(Yx.KEY_URL) + UserLoginResponse.getPhoneNum(HomePageActivity.this);
				fixedUrl += NwUtils.webTail();
				intent.putExtra(Yx.KEY_URL, fixedUrl);
				Utils.logd("AD url =" + fixedUrl);
				Utils.logd("AD title = " + arg2.getExtras().getString(Yx.KEY_TITLE));
				startActivity(intent);
				break;
			default:
				break;
			}
		}
	} 
	
	private View.OnClickListener mClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.city_name:
			case R.id.city_indicator:
				Intent intent;
				// do nothing, only support Beijing Now!!
				StatHelper.addKVEvent(mContext, "event_home_city_switch_click");
				UIHelper.showTips(arg0, "目前只支持北京地区");
//				Intent intent = new Intent(getApplicationContext(), CitySwitchActivity.class);
//				startActivityForResult(intent, REQUEST_CODE_GET_CITY_NAME);
				break;
			case R.id.search_box:
				intent = new Intent(getApplicationContext(), CourseSearchActivity.class);
				StatHelper.addKVEvent(mContext, "event_search_box_click");
				startActivity(intent);
				break;
			case R.id.settings:
				StatHelper.addKVEvent(mContext, "event_home_settings_click");
				startActivity(new Intent(getApplicationContext(), MyPageActivity.class));
				break;
			case R.id.login:
				if (arg0 instanceof TextView) {
					
					TextView textView = (TextView) arg0;
					updateText(textView);
					
					if ("登录".equals(textView.getText().toString())) {
						intent = new Intent(getApplicationContext(),
								UserLoginActivity.class);
						startActivityForResult(intent, REQUEST_CODE_LOGIN);
					} else {
						// do nothing
					}
				}
				break;
			default:
				mBaseClickListener.onClick(arg0);
				break;
			}
		}
	};
	
	
	private void customizeSearchActionBar(int resId, String title) {
		customizeSearchActionBar(resId);
		TextView titleText = (TextView) mActionBar.getCustomView().findViewById(R.id.title);
		titleText.setText(mKeyName.get(title));
	}
	
	private View getIndicatorView(String name, int layoutId) {
		View v = getLayoutInflater().inflate(layoutId, null);
		TextView tv = (TextView) v.findViewById(R.id.tabText);
		tv.setText(name);
		return v;
	}
	
	// Double press back key to exit the application.
	@Override
	public void onBackPressed() {
		pressedTimes++;
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				pressedTimes = 0;
			}
		}, Yx.EXTI_TIMEOUT);
		if (pressedTimes == 1) {
			Toast.makeText(this, R.string.press_to_exit, Toast.LENGTH_SHORT).show();
			;
			return;
		} else if (pressedTimes >= 2) {
			HomePageActivity.this.finish();
			// 尝试关闭地图
	        Utils.tryCloseGps(this);
	        System.exit(0);
		}
		return;
	}

	private void addHomePageListener() {
		int[] ids2 = new int[] {
				R.id.city_name,
				R.id.city_indicator,
				R.id.search_box,
				R.id.settings,
				R.id.login
		};
		for (int id : ids2) {
			UIHelper.setClickListener(mActionBar.getCustomView(), id, mClickListener);
		}
	}
	
	private void updateText(TextView textView) {
		boolean isLogin = Utils.isLogin(getApplicationContext());
		if (isLogin)
		{
			//说明已经登录。
			textView.setText("已登录");
		} else {
			textView.setText("登录");
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		// PUSH Activity
		try {
			Bundle bundle = getIntent().getExtras();
			String custom = bundle.getString(Yx.KEY_PUSH_EXTRA_CUSTOM);
			getIntent().putExtra(Yx.KEY_PUSH_EXTRA_CUSTOM, "");
			PushHelper.pushActivity(this, custom);
		} catch (Exception e) {
			// do nothing
		}
		
		//
		Utils.logd( "CMM7 ,channelCode = " + Utils.getChannelCode(this));
		// 将数据传到server
		if (!(Utils.getNetworkInfo(this) == Utils.NW_TYPE_NO_CONN)) {
			if (isUploadingData) {
				return;
			}
			isUploadingData = true;
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					ArrayList<DMCallRecord> records = YxDataBase.getInstance(
							HomePageActivity.this).queryAllCallRecord();
					for (DMCallRecord record : records) {
						ResponseObject code = new ResponseObject(-1, "");
						try {
							code = NwUtils.submitCallBehavior(HomePageActivity.this, record);
						} catch (ClientProtocolException e) {
							e.printStackTrace();
						} catch (ParseException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						} catch (JSONException e) {
							e.printStackTrace();
						}
						// 上传成功删掉该条记录。
						if (code.getCode() == MsgCode.SUCCESS) {
							Utils.logd("record submit ok = " + record.toString());
							YxDataBase.getInstance(HomePageActivity.this).deleteCallRecord(record);
						}
						// 尝试提交openApp记录并删掉
					}
					
					ArrayList<DMOpenApp> openApps = YxDataBase.getInstance(
							HomePageActivity.this).queryOpenAppRecord();
					for (DMOpenApp item : openApps) {
						ResponseObject code = new ResponseObject(-1, "");
						try {
							code = NwUtils.submitOpenAppBehavior(HomePageActivity.this, item);
						} catch (ClientProtocolException e) {
							e.printStackTrace();
						} catch (ParseException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						} catch (JSONException e) {
							e.printStackTrace();
						}
						// 上传成功删掉该条记录。
						if (code.getCode() == MsgCode.SUCCESS) {
							Utils.logd("openApp record submit ok = " + item.toString());
							YxDataBase.getInstance(HomePageActivity.this).deleteOpenAppRecord(item);
						}
					}
					isUploadingData = false;
				}
			}).start();
			
		}
		
		// App访问5次时，弹框条件。
		if (Utils.getAppOpenTime(this) == 5) {
			Utils.writeToSharePreference(this, Yx.KEY_HAS_APPOINT_OR_BUY_OR_COMMENT, "1");
		}
		// 根据情况提示用户进行评分。
		Utils.askUserToScore(this);
		
		//MTA
		StatHelper.addKVEvent(mContext, "event_home_resume");

		// 获取mac地址
		
//		MacAddrHelper.getMacFromCallCmd();
//		MacAddrHelper.getMacFromWifi(this);
	}
	
	/**
	 * 网络加载失败重新刷新页面
	 * @param view
	 */
	public void toRefresh(View view) {
		 Fragment home = getSupportFragmentManager().findFragmentById(R.id.home_fragment);
		if (home != null && (home instanceof HomePageFragment)) {
			((HomePageFragment) home).toRefresh(view);
		}
	}



}
